#!/usr/bin/env python3
"""
DataPlexus 数据源管理路由配置脚本
在动态路由系统中添加数据源管理页面路由
"""

import sys
import os
import asyncio
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_
from app.core.database import get_async_session
from app.models.auth import Route, RoutePermission, Permission
from app.core.logger import logger


class DataSourceRouteInitializer:
    """数据源路由初始化器"""
    
    def __init__(self):
        self.route_data = {
            'path': '/datasources',
            'name': 'datasources',
            'display_name': '数据源管理',
            'description': '数据库连接配置管理',
            'icon': 'DatabaseOutlined',
            'component': 'DataSourceManagement',
            'is_menu': True,
            'is_active': True,
            'sort_order': 30,  # 在系统管理模块中的排序
            'parent_path': '/system',  # 父路由路径
            'meta': {
                'title': '数据源管理',
                'icon': 'DatabaseOutlined',
                'requiresAuth': True,
                'keepAlive': True,
                'showInMenu': True
            }
        }
        
        # 需要关联的权限
        self.required_permissions = [
            'datasource.view'  # 访问页面的基本权限
        ]
    
    async def create_route(self, db: AsyncSession) -> dict:
        """创建数据源管理路由"""
        try:
            # 检查路由是否已存在
            stmt = select(Route).where(Route.path == self.route_data['path'])
            result = await db.execute(stmt)
            existing_route = result.scalar_one_or_none()
            
            if existing_route:
                # 更新现有路由
                existing_route.name = self.route_data['name']
                existing_route.display_name = self.route_data['display_name']
                existing_route.description = self.route_data['description']
                existing_route.icon = self.route_data['icon']
                existing_route.component = self.route_data['component']
                existing_route.is_menu = self.route_data['is_menu']
                existing_route.is_active = self.route_data['is_active']
                existing_route.sort_order = self.route_data['sort_order']
                existing_route.meta = self.route_data['meta']
                existing_route.updated_at = datetime.utcnow()
                
                logger.info(f"更新路由: {self.route_data['path']}")
                route = existing_route
                action = 'updated'
            else:
                # 获取父路由ID（如果有父路由）
                parent_id = None
                if self.route_data.get('parent_path'):
                    parent_stmt = select(Route).where(Route.path == self.route_data['parent_path'])
                    parent_result = await db.execute(parent_stmt)
                    parent_route = parent_result.scalar_one_or_none()
                    if parent_route:
                        parent_id = parent_route.id
                
                # 创建新路由
                route = Route(
                    path=self.route_data['path'],
                    name=self.route_data['name'],
                    display_name=self.route_data['display_name'],
                    description=self.route_data['description'],
                    icon=self.route_data['icon'],
                    component=self.route_data['component'],
                    parent_id=parent_id,
                    is_menu=self.route_data['is_menu'],
                    is_active=self.route_data['is_active'],
                    sort_order=self.route_data['sort_order'],
                    meta=self.route_data['meta'],
                    created_at=datetime.utcnow(),
                    updated_at=datetime.utcnow()
                )
                db.add(route)
                
                logger.info(f"创建路由: {self.route_data['path']}")
                action = 'created'
            
            await db.commit()
            await db.refresh(route)
            
            return {
                'action': action,
                'route_id': route.id,
                'route_path': route.path,
                'route_name': route.name
            }
            
        except Exception as e:
            await db.rollback()
            logger.error(f"创建路由失败: {str(e)}")
            raise
    
    async def assign_permissions_to_route(self, db: AsyncSession, route_id: int) -> dict:
        """为路由分配权限"""
        assigned_count = 0
        skipped_count = 0
        
        try:
            for permission_name in self.required_permissions:
                # 获取权限
                perm_stmt = select(Permission).where(Permission.name == permission_name)
                perm_result = await db.execute(perm_stmt)
                permission = perm_result.scalar_one_or_none()
                
                if not permission:
                    logger.warning(f"权限不存在: {permission_name}")
                    continue
                
                # 检查路由权限关联是否已存在
                rp_stmt = select(RoutePermission).where(
                    and_(
                        RoutePermission.route_id == route_id,
                        RoutePermission.permission_id == permission.id
                    )
                )
                rp_result = await db.execute(rp_stmt)
                existing_rp = rp_result.scalar_one_or_none()
                
                if existing_rp:
                    # 确保关联是活跃的
                    if not existing_rp.is_active:
                        existing_rp.is_active = True
                        existing_rp.updated_at = datetime.utcnow()
                        logger.info(f"激活路由权限关联: {permission_name}")
                    skipped_count += 1
                    continue
                
                # 创建路由权限关联
                route_permission = RoutePermission(
                    route_id=route_id,
                    permission_id=permission.id,
                    is_required=True,
                    is_active=True,
                    created_at=datetime.utcnow()
                )
                db.add(route_permission)
                assigned_count += 1
                logger.info(f"为路由分配权限: {permission_name}")
            
            await db.commit()
            
            return {
                'assigned': assigned_count,
                'skipped': skipped_count
            }
            
        except Exception as e:
            await db.rollback()
            logger.error(f"分配路由权限失败: {str(e)}")
            raise
    
    async def verify_route_configuration(self, db: AsyncSession) -> dict:
        """验证路由配置"""
        try:
            # 获取数据源管理路由
            route_stmt = select(Route).where(Route.path == self.route_data['path'])
            route_result = await db.execute(route_stmt)
            route = route_result.scalar_one_or_none()
            
            if not route:
                raise Exception("数据源管理路由未找到")
            
            # 获取路由权限关联
            rp_stmt = select(RoutePermission).join(Permission).where(
                RoutePermission.route_id == route.id
            )
            rp_result = await db.execute(rp_stmt)
            route_permissions = rp_result.scalars().all()
            
            # 获取关联的权限详情
            permissions = []
            for rp in route_permissions:
                perm_stmt = select(Permission).where(Permission.id == rp.permission_id)
                perm_result = await db.execute(perm_stmt)
                permission = perm_result.scalar_one_or_none()
                if permission:
                    permissions.append({
                        'name': permission.name,
                        'display_name': permission.display_name,
                        'is_required': rp.is_required,
                        'is_active': rp.is_active
                    })
            
            verification_result = {
                'route': {
                    'id': route.id,
                    'path': route.path,
                    'name': route.name,
                    'display_name': route.display_name,
                    'component': route.component,
                    'is_menu': route.is_menu,
                    'is_active': route.is_active,
                    'sort_order': route.sort_order
                },
                'permissions': permissions,
                'permissions_count': len(permissions)
            }
            
            return verification_result
            
        except Exception as e:
            logger.error(f"验证路由配置失败: {str(e)}")
            raise
    
    async def run(self):
        """运行路由初始化"""
        logger.info("开始初始化数据源管理路由...")
        
        try:
            async with get_async_session() as db:
                # 创建路由
                logger.info("创建数据源管理路由...")
                route_result = await self.create_route(db)
                logger.info(f"路由创建完成: {route_result}")
                
                # 分配权限给路由
                logger.info("分配权限给路由...")
                assign_result = await self.assign_permissions_to_route(db, route_result['route_id'])
                logger.info(f"权限分配完成: {assign_result}")
                
                # 验证结果
                logger.info("验证路由配置...")
                verify_result = await self.verify_route_configuration(db)
                logger.info(f"验证结果: {verify_result}")
                
                logger.info("数据源管理路由初始化完成！")
                
                return {
                    'route': route_result,
                    'permissions': assign_result,
                    'verification': verify_result
                }
                
        except Exception as e:
            logger.error(f"路由初始化失败: {str(e)}")
            raise


async def main():
    """主函数"""
    try:
        initializer = DataSourceRouteInitializer()
        result = await initializer.run()
        
        print("\n" + "="*60)
        print("DataPlexus 数据源管理路由初始化完成")
        print("="*60)
        print(f"路由操作: {result['route']['action']}")
        print(f"路由ID: {result['route']['route_id']}")
        print(f"路由路径: {result['route']['route_path']}")
        print(f"路由名称: {result['route']['route_name']}")
        print(f"分配权限: {result['permissions']['assigned']}")
        print(f"跳过权限: {result['permissions']['skipped']}")
        print(f"关联权限数: {result['verification']['permissions_count']}")
        print("="*60)
        
        return True
        
    except Exception as e:
        print(f"\n❌ 路由初始化失败: {str(e)}")
        return False


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)
